<template>
  <view class="content-img">
    <eui-nav-bar title="蓝牙打印机" color="#333" rightIcon="" />
  </view>
  <view class="main-view padding-top-20 font-size-28" :style="{width:scrollWidth,height:scrollHeight}">
    <view class="color-888">已连接的打印机</view>
    <view class="background-color-fff border-radius-20 margin-top-12">
      <view v-show="bluetoothPrinter.printerName" class="item">
        <view class="left">
          <view>{{bluetoothPrinter.printerName}}</view>
          <view class="color-888">{{bluetoothPrinter.deviceId}}</view>
        </view>
        <view class="right">
          <eui-button type="min2" minWidth="100" @buttonClick="disconnect" title="断开" :fontColor="'#ff4000'" :borderColor="'#ff4000'" />
        </view>
      </view>
      <view v-show="!bluetoothPrinter.printerName" class="item">
        <view class="left">
          <text>未连接打印机</text>
        </view>
      </view>
    </view>
    <view class="margin-top-20 color-888">可连接的打印机</view>
    <scroll-view class="overflow-hidden margin-top-12 border-radius-20" scroll-y="true" :style="{width:scrollWidth,height:scrollHeight1}">
      <view v-show="printerList && printerList.length > 0" class="background-color-fff border-radius-20">
        <view class="item" v-for="(item, index) in printerList">
          <view class="left">
            <view>{{item.printerName}}</view>
            <view class="color-888">{{item.deviceId}}</view>
          </view>
          <view class="right">
            <eui-button type="min" minWidth="100" @buttonClick="connect(item)" title="连接"/>
          </view>
        </view>
      </view>
      <view class="no-data flex-column-between"  v-show="!printerList || printerList.length === 0">
        <image src="@/static/img/no_data.png" mode="aspectFit" class="image" />
        <view class="color-888 font-size-28">暂未搜索到蓝牙设备</view>
      </view>
    </scroll-view>
  </view>
  <view class="fixed-bottom" :class="[theme]">
    <view class="refresh" @click="searchPrinter">
      搜索
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import {onReady} from '@dcloudio/uni-app';
import {usePrinterStore} from "@/store/printerStore";
import {storeToRefs} from "pinia";
import BluetoothPrinter from '@/common/BluetoothPrinter';
import { useThemeStore } from '@/store/themeStore';

// 使用 store 获取主题
const themeStore = useThemeStore();
const { theme } = storeToRefs(themeStore);

const scrollWidth = ref(uni.getSystemInfoSync().windowWidth - 20 + 'px');
const scrollHeight = ref(uni.getSystemInfoSync().windowHeight + 'px');
const scrollHeight1  = ref(uni.getSystemInfoSync().windowHeight + 'px');
const printerStore = usePrinterStore();

const {bluetoothPrinter} = storeToRefs(printerStore);

const printerList:any = ref([]);

const disconnect = () => {
  console.log("disconnect====>bluetoothPrinter.value.deviceId",bluetoothPrinter.value.deviceId);
  if(bluetoothPrinter.value.deviceId){
    BluetoothPrinter.closeConnect(bluetoothPrinter.value.deviceId).finally(()=> {
      let printer:any = {
        connected: false,
        printerName: "",
        deviceId: "",
        writeCharaterId: "",
        writeServiceId: "",
        notifyCharaterId: "",
        notifyServiceId: "",
        readCharaterId: "",
        readServiceId: "",
        printDelayTime: 20,
      };
      printerStore.setBluetoothPrinter(printer);
    })
  }
}

const connect = (printer:any) => {
  console.log("connect====>", printer);

  uni.showLoading({title: '连接中...'});
  BluetoothPrinter.connect(printer.deviceId).then((res: any) => {
    BluetoothPrinter.init(printer.deviceId).then((res: any) => {
      console.log("connect====>res",res);
      let connectedPrinter:any = {
        connected: true,
        ...res,
        ...printer
      };
      console.log("init====>then,connectedPrinter",connectedPrinter);
      printerStore.setBluetoothPrinter(connectedPrinter);
      uni.hideLoading();
    }).catch((res:any) => {
      console.log("init====>catch,res",res);
      uni.hideLoading();
    });
  }).catch((res: any) => {
    console.log("connect====>catch,res",res);
    uni.hideLoading();
  });

}

const searchPrinter = () => {
  // #ifndef H5
  uni.showLoading({title:'搜索中...'});
  BluetoothPrinter.openAdapter().then((res:any) => {
    BluetoothPrinter.startSearch().then((res:any) => {
      let devices = res;

      let searchedDevices: { deviceId: string, printerName: string }[] = [];
      devices.forEach((item:any) => {
        searchedDevices.push({deviceId: item.deviceId, printerName: item.name});
      })

      console.log('searchedDevice', searchedDevices);
      printerList.value = searchedDevices;
    }).finally(()=> {
      uni.hideLoading();
    })
  }).catch((res:any) => {
    uni.showToast({
      duration: 3000,
      icon: 'none',
      title: "当前环境暂不支持蓝牙设备"
    });
    console.log('startSearch---catch:res', res);
  })
  // #endif

  // #ifdef H5
  uni.showToast({
    duration: 3000,
    icon: 'none',
    title: "当前环境暂不支持蓝牙设备"
  });
  // #endif
}


onReady(()=>{
  uni.getSystemInfo({
    success: function(res) {
      const userInfoPage = uni.createSelectorQuery().select(".content-img");
      userInfoPage.boundingClientRect(function(data:any) {
        scrollHeight.value = (res.windowHeight - data.height - 20)+'px';
        scrollHeight1.value = (res.windowHeight - data.height - 200)+'px';
      }).exec()
    }
  });
})
</script>

<style lang="scss" scoped>
@import '@/main.scss';

.content-img {
  background-color: #FFFFFF;
  background-repeat: no-repeat;
  width: 100%;
}

.main-view {
  flex: 1;
  flex-direction: column;
  padding: 0 20rpx;
  background-color: #f2f2f2;
}

.flex {
  display: flex;
}

.font-size-28 {
  font-size: 28rpx;
}

.setting-logOut {
  display: flex;
  width: 100%;
  height: 100rpx;
  margin: 0 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  justify-content: center;
  align-items: center;
  color: var(--theme-color);
  font-size: 26rpx;
}

.padding-all-28 {
  padding: 28rpx;
}

.background-color-fff {
  background-color: #fff;
}

.border-radius-20 {
  border-radius: 20rpx;
}

.padding-top-20{
  padding-top:20rpx;
}

.margin-top-20 {
  margin-top: 20rpx;
}

.margin-top-12 {
  margin-top: 12rpx;
}

.color-888 {
  color: rgba(136, 136, 136, 1);
}

.main-theme {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  margin-right: 32rpx;
  position: relative;
}

.main-body .main-theme:last-child {
  margin-right: 0;
}

.main-theme-sel {
  width: 25px;
  height: 25px;
  background: #ffffff;
  clip-path: polygon(100% 10%, 100% 100%, 10% 100%);
  position: absolute;
  bottom: 0;
  right: 0;
}

.main-theme-icon {
  position: absolute;
  bottom: 0;
  right: 0;
}

.overflow-hidden {
  overflow: hidden;
}

.padding-left-28 {
  padding-left: 28rpx;
}
.item {
  border-bottom: 0.03125rem solid rgb(238, 238, 238);
  padding: 0.75rem;
  display: flex;
  flex-direction: row;
  width: 100%;
  box-sizing: border-box;
}
.item .left {
  flex: 1;
  align-self: center;
}
.item .right{
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.fixed-bottom {
  position: fixed;
  bottom: 10rpx;
  left: 0;
  width: 100%;
  height: 50px;
  display: flex;
}
.refresh{
  position: absolute;
  width: 3.6rem;
  height: 3.6rem;
  line-height: 3.6rem;
  text-align: center;
  border-radius: 1.8rem;
  top: -2.2rem;
  background-color: var(--theme-color);
  color: rgb(255, 255, 255);
  left: 50%;
  transform: translate(-50%);
}
.text-center{
  text-align: center;
  height: 55rpx;
  line-height: 55rpx;
}
.no-data {
  background-color: RGBA(255,255,255,0);
}
</style>